package com.meng.netty.server;

import com.meng.netty.decoder.PointOfSaleDecoder;
import com.meng.netty.encoder.PointOfSaleEncoder;
import com.meng.netty.handler.PointOfSaleHandler;
import com.meng.redis.thread.SyncRedisDataToMysqlThread;
import com.meng.util.PublishNettyServer;
import com.meng.util.ThreadPoolUtil;
import com.meng.util.Utils;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;

import java.io.IOException;
import java.util.concurrent.TimeUnit;


/**
 * POS 服务端  echo:有响应的服务
 *
 * @author MENG
 * @version 2018/3/19
 * @see
 */
@PublishNettyServer
public class PointOfSaleServer extends NettyServer
{
    public PointOfSaleServer() throws IOException
    {
        //传入 端口 和 通道
        super(Integer.parseInt(Utils.getNettyPropsValByKey("pos.server.port")), new ChannelInitializer<SocketChannel>() {

            @Override
            public void initChannel(SocketChannel ch) throws Exception
            {
                //设置读空闲超时时间 READ_IDLE_TIME channelRead()方法超过readerIdleTime时间未被调用则会触发超时事件调用userEventTrigger()方法
//                ch.pipeline().addLast("ping", new IdleStateHandler(PointOfSaleConstant.READ_IDLE_TIME,

//                    PointOfSaleConstant.WRITE_IDLE_TIME, PointOfSaleConstant.ALL_IDLE_TIME, TimeUnit.SECONDS));

                // 属于ChannelOutboundHandler，逆序执行
                ch.pipeline().addLast(new PointOfSaleEncoder());

                // 属于ChannelInboundHandler，按照顺序执行
                ch.pipeline().addLast(new PointOfSaleDecoder());

                ch.pipeline().addLast(new PointOfSaleHandler());
            }

        });

        //启动redis数据同步mysql定时器
        ThreadPoolUtil.getSyncRedisDataToMysqlSingleScheduledThreadPool().scheduleWithFixedDelay(new SyncRedisDataToMysqlThread(),10,10,
            TimeUnit.SECONDS);

    }
}
